<?php
/**
 * Created by PhpStorm.
 * User: Knight
 * Date: 2019/2/18
 * Time: 11:24
 */

namespace app\api\service;

use app\api\exception\PrizeException;
use app\api\model\UserDrawConf as UserDrawConfModel;
use app\api\model\PrizeConf as PrizeConfModel;
use app\api\model\UserPrize as UserPrizeModel;
use app\api\model\PrizeCode as PrizeCodeModel;

class Prize
{

    /**
     * 用户抽奖
     * @param $unionid
     */
    public function draw($unionid)
    {
        $userDrawConfModel = new UserDrawConfModel();
        $zdUserDrawConf = $userDrawConfModel->where('unionid', $unionid)->find();
        $zdUserDrawConf->startTrans();
        //验证用户是否可以抽奖
        if (empty($zdUserDrawConf) || $zdUserDrawConf['num'] <= 0) {
            throw new PrizeException(['errorCode' => 60001, 'msg' => '无抽奖次数']);
        }
        $prizeid = $this->drawPrize($unionid);

        //减抽奖次数
        $zdUserDrawConf['num']-=1;
        $res0=$zdUserDrawConf->save();


        if ($prizeid == 999) {
            //未中奖
            $zdUserDrawConf->commit();
            return ['code' => 2, 'msg' => '未中奖','drawNum'=>$zdUserDrawConf['num']];
        }
        if($prizeid==1){
            //抽到邀请码
            $prizeCodeModel=new PrizeCodeModel();
            $prizeCodeMsg=$prizeCodeModel->lock(true)->where('unionid is null or unionid=""')->find();
            $prizeCodeMsg->startTrans();
            $prizeCodeMsg->unionid=$unionid;
            $prizeCodeMsg->updated_time=date('Y-m-d H:i:s');
            $res3=$prizeCodeMsg->save();
            $prizeCode=$prizeCodeMsg->code;

        }else{
            $res3=true;
        }

        //1.减库存
        $prizeConfModel = new PrizeConfModel();
        $prizeConf = $prizeConfModel->lock(true)->where('id', $prizeid)->find();
        $prizeConf->startTrans();
        $prizeConf->number = intval($prizeConf->number) - 1;
        $res1 = $prizeConf->save();

        //2.记录用户中奖
        $userPrizeModel = new  UserPrizeModel();
        $userPrizeModel->startTrans();
        $res2=$userPrizeModel->save([
           'unionid'=>$unionid,
           'prize_name'=>$prizeConf->name,
           'prize_image'=>$prizeConf->image,
           'prize_describe'=>$prizeConf->describe,
           'prize_attention'=>$prizeConf->attention,
           'prize_code'=>empty($prizeCode)?'':$prizeCode,
           'prize_type'=>$prizeConf->prize_type,
           'prize_status'=>1,
           'created_time'=>date('Y-m-d H:i:s'),
        ]);

        if($res1 && $res2 && $res0 && $res3){
            $prizeConf->commit();
            $userPrizeModel->commit();
            $zdUserDrawConf->commit();
            if(!empty($prizeCodeMsg)){
                $prizeCodeMsg->commit();
            }
            return ['code' => 1, 'prize' => [
                'name'=>$prizeConf->name,
                'image'=>$prizeConf->image,
                'describe'=>$prizeConf->describe,
                'attention'=>$prizeConf->attention,
                'prizetype'=>$prizeConf->prize_type,
                'prizecode'=>empty($prizeCode)?'':$prizeCode
                ],
                'drawNum'=>$zdUserDrawConf['num']
            ];
        }else{
            $prizeConf->rollback();
            $userPrizeModel->rollback();
            $zdUserDrawConf->rollback();
            if(!empty($prizeCodeMsg)){
                $prizeCodeMsg->rollback();
            }
            throw new PrizeException(['errorCode' => 60002, 'msg' => '抽奖失败，请重试']);
        }

    }

    /**
     * 抽奖
     * @param $unionid
     */
    private function drawPrize($unionid)
    {
        $prizeConfModel = new PrizeConfModel();
        $prizeArr = $prizeConfModel->select();

        //获得奖品库存大于0的奖品
        $arr = [];
        $other = ['id' => 999, 'prize_chance' => 10000];
        for ($i = 0; $i < count($prizeArr); $i++) {
            if ($prizeArr[$i]['number'] > 0) {
                $arr[] = $prizeArr[$i];
                $other['prize_chance'] -= $prizeArr[$i]['prize_chance'];
            }
        }
        $arr[] = $other;
        for ($j = 0; $j < count($arr); $j++) {
            $prize_chance = $arr[$j]['prize_chance'];
            for ($ei = 0; $ei < $prize_chance; $ei++) {
                $return[] = $arr[$j]['id'];
            }
        }

        shuffle($return);
        return $return[array_rand($return)]; //中奖序号

    }

    /**
     * 用户抽奖记录查询
     * @param $unionid
     */
    public function checkprize($unionid)
    {
        $userPrizeModel = new  UserPrizeModel();
        $prizeArr=$userPrizeModel->where('unionid',$unionid)
            ->field('id,prize_name,prize_image,prize_describe,prize_attention,prize_type,prize_status,prize_code,created_time')
            ->order('created_time','desc')
            ->select();
        return ['code' => 1, 'prizelist' => $prizeArr];

    }

    /**
     * 工作人员领取奖品
     * @param $unionid
     */
    public function getprize($unionid,$prizeid)
    {
        $userPrizeModel = new  UserPrizeModel();
        $userprize=$userPrizeModel
            ->where('unionid',$unionid)
            ->where('id',intval($prizeid))
            ->find();

        if(empty($userprize)){
            throw new PrizeException(['errorCode' => 60003, 'msg' => '领取失败，请重试']);
        }
        if($userprize['prize_status']==2){
            throw new PrizeException(['errorCode' => 60004, 'msg' => '已领取过,无需重复领取']);
        }

        $userprize->prize_status=2;
        $userprize->updated_time=date('Y-m-d H:i:s');
        $userprize->save();
        return ['code' => 1, 'msg' => '领取成功'];
    }

    /**
     * 获取奖品信息
     */
    public function getPrizeList()
    {
        $prizeConfModel=new  PrizeConfModel();
        $prizeList=$prizeConfModel->field('id,name,image,describe,attention,prize_type')->select();
        return ['code' => 1, 'prizeList' => $prizeList];
    }


}